package com.meitianhui.convenitenbuy.module.store.presenter;

import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseResponse;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.http.ResponseObserver;
import com.meitianhui.convenitenbuy.main.http.MainApiDataSource;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.module.mine.model.UserAsset;
import com.meitianhui.convenitenbuy.module.store.contract.ShopCarPayContract;
import com.meitianhui.convenitenbuy.module.store.model.ShopCarGoods;
import com.meitianhui.convenitenbuy.module.store.ui.activity.ShopCarPayActivity;
import com.meitianhui.convenitenbuy.module.wallet.http.WalletApiDataSource;
import com.meitianhui.convenitenbuy.module.wallet.model.AlipayResultBean;
import com.meitianhui.convenitenbuy.module.wallet.model.PayResultBean;
import com.meitianhui.convenitenbuy.module.wallet.model.RechargeBackInfoBean;
import com.meitianhui.convenitenbuy.util.DateUtil;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.StringUtils;
import com.meitianhui.convenitenbuy.util.SystemUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class ShopCarPayPresenter implements ShopCarPayContract.Presenter {

    private ShopCarPayActivity mContext;
    private ShopCarPayContract.View view;
    private final IWXAPI wxApi;

    public ShopCarPayPresenter(ShopCarPayContract.View view, ShopCarPayActivity context) {
        this.view = view;
        this.mContext = context;
        wxApi = WXAPIFactory.createWXAPI(context, Constants.WX_APP_ID, true);
    }

    @Override
    public void getUserAsset() {
        Map<String, String> map = new HashMap<>();
        map.put("member_id", InfoProvider.getUserToken(mContext).getMember_id());
        String json = new Gson().toJson(map);

        MainApiDataSource.getInstance()
                .getUserAsset(InfoProvider.getUserToken(mContext).getUser_token(),
                        "finance.memberAssetFind", json)
                .subscribe(new ResponseObserver<BaseResponse<UserAsset>>(mContext) {
                    @Override
                    public void onSuccess(BaseResponse<UserAsset> response) {
                        view.getUserAssetSuccess(response.data);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                    }
                });
    }

    @Override
    public void orderPay(int payWay, String storeId, String storeName, String receiveName,
                         String receivePhone, String receiveAddress, String totalPrice,
                         String payPrice, String allValueReturn, String feedBack,
                         List<ShopCarGoods> list) {
        String desc = "";
        Map<String, String> params = new HashMap<>();
        if (payWay == 0) {
            params.put("payment_way_key", Constants.PAYMENT_WAY_05);
        } else if (payWay == 1) {
            params.put("payment_way_key", Constants.ALIPAY_APY);
        } else if (payWay == 2) {
            params.put("payment_way_key", Constants.WECHAT_APY);
        }
        params.put("data_source", Constants.CUSTOM_APP);
        if (list.size() > 0) {
            String s_name = list.get(0).getName();
            if (!TextUtils.isEmpty(s_name)) {
                desc = s_name + " ";
            }
        }
        desc = StringUtils.StringFilter(desc);
        params.put("detail", "精选特卖");
        params.put("amount", totalPrice);//总金额
        params.put("buyer_id", InfoProvider.getUserToken(App.getInstance()).getMember_id());
        params.put("seller_id", Constants.SELLER_ID);
        params.put("order_type_key", "DDLX_04");//表示C端
        params.put("transaction_date", DateUtil.getyyyyMMddHHmmss());//表示C端
        Map<String, String> params2 = new HashMap<>();
        params2.put("desc1", desc);
        params2.put("contact_person", receiveName);//联系人
        params2.put("contact_tel", receivePhone);//联系电话
        params2.put("total_fee", totalPrice);//优惠后的价格
        params2.put("delivery_address", receiveAddress);//收货地址
        params2.put("discount_fee", "0.00");//优惠了多少钱
        params2.put("rebate_fee", allValueReturn);//总返利了多少钱
        params2.put("consumer_id", InfoProvider.getUserToken(App.getInstance()).getMember_id());
        params2.put("stores_id", storeId);//商家ID
        params2.put("item_num", list.size() + "");//总数量
        params2.put("sale_fee", payPrice);//没有优惠的价格
        params2.put("stores_name", storeName);//店的名称
        if (!TextUtils.isEmpty(feedBack)) {
            params2.put("remark", feedBack);//意见
        }
        JSONArray array = new JSONArray();
        for (int i = 0; i < list.size(); i++) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("item_store_id", list.get(i).getItemId());
                jsonObject.put("qty", list.get(i).getNum());
                jsonObject.put("sale_price", list.get(i).getPrice());
                jsonObject.put("discount_fee", list.get(i).getPrice());
                jsonObject.put("total_fee", StringUtils.moneyMul(list.get(i).getNum(), list.get(i).getPrice()));
                jsonObject.put("rebate", list.get(i).getRebate());
                array.put(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        params2.put("store_item_list", array.toString());
        params.put("out_trade_body", new Gson().toJson(params2));
        String paramJson = new Gson().toJson(params);

        WalletApiDataSource.getInstance()
                .getRechargeOrder(InfoProvider.getUserToken(App.getInstance()).getUser_token(),
                        "finance.orderPay", paramJson)
                .subscribe(new ResponseObserver<BaseResponse<RechargeBackInfoBean>>(mContext, true) {
                    @Override
                    public void onSuccess(BaseResponse<RechargeBackInfoBean> response) {
                        RechargeBackInfoBean result = response.data;
                        if (payWay == 1) {
                            wakeUpAliPay(result);
                        } else if (payWay == 2) {
                            wakeUpWeChat(result);
                        } else {
                            view.walletPaySuccess();
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        view.onFail(code, msg);
                    }
                });
    }

    private void wakeUpAliPay(RechargeBackInfoBean bean) {
        String orderInfo = bean.getAlipay_params();
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                PayTask alipay = new PayTask(mContext);
                String result = alipay.pay(orderInfo, true);
                emitter.onNext(result);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                AlipayResultBean payResult = new AlipayResultBean(s);
                String resultInfo = payResult.getResult();
                String resultStatus = payResult.getResultStatus();
                // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                if (TextUtils.equals(resultStatus, "9000")) {
                    TipUtils.showToast(App.getInstance(), mContext.getString(R.string.wallet_change_recharge_success), 3);
                    RxBus.get().post(new PayResultBean(Constants.PAY_RESULT_SUCCESS));
                    RxBus.get().post(new EventBean(Constants.EVENT_TYPE_REFRESH));//钱包刷新
                } else {
                    // 判断resultStatus 为非“9000”则代表可能支付失败
                    // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，
                    // 最终交易是否成功以服务端异步通知为准（小概率状态）
                    if (TextUtils.equals(resultStatus, "8000")) {
                        TipUtils.showToast(App.getInstance(), mContext.getString(R.string.wallet_change_recharge_confirming), 3);
                    } else {
                        // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                        TipUtils.showToast(App.getInstance(), mContext.getString(R.string.wallet_change_recharge_fail));
                    }
                }
            }
        });
    }

    private void wakeUpWeChat(RechargeBackInfoBean result) {
        boolean ifInstall = SystemUtils.isWXAppInstalledAndSupported(mContext, result.getAppid());
        if (!ifInstall) {
            TipUtils.showToast(App.getInstance(), mContext.getString(R.string.wallet_change_recharge_order_wechat_uninstall));
            return;
        }
        PayReq req = new PayReq();
        req.appId = result.getAppid();
        req.nonceStr = result.getNoncestr();
        req.packageValue = result.getPackageValue();
        req.partnerId = result.getPartnerid();
        req.prepayId = result.getPrepayid();
        req.timeStamp = result.getTimestamp();
        req.sign = result.getSign();
        wxApi.registerApp(result.getAppid());
        wxApi.sendReq(req);
    }

    @Override
    public void attachView(Object view) {
    }

    @Override
    public void detachView() {
    }

}
